<template>
	<view class="com_wrapper">
		<!-- 	<view class="com_title">点击进入维保公司</view>
		<view class="com_item" @click="toIndex(item)" v-for="item in userCompanyList" :key="item.userId">
			<view class="item_L">
				<text>{{ item.companyName }}</text>
				<text>{{ item.realName }}</text>
			</view>
			<view class="item_R"><text></text></view>
		</view> -->
		<view class="switch_role">
			<view class="switch_role_content">
				<view class="left">
					<view class="header">我的公司</view>
					<view class="companyList">
						<view class="companyList_item" v-for="(item, index) in userCompanyList" :key="index"
							@click="changeCompany(item, index)" :class="[index === companyId ? 'activeCom' : '']">
							{{ item.companyName }}
						</view>
					</view>
				</view>
				<view class="right">
					<view class="header">我的角色</view>
					<view class="companyList">
						<view class="companyList_item" v-for="(item, index) in roleList" :key="index"
							:class="[item.id === roleId ? 'activeCom' : '']" @click="changeRole(item)">
							{{ realName + '(' + item.roleName + ')' }}
						</view>
					</view>
				</view>
			</view>
			<view class="bottom">
				<view class="submit" @click="toIndex">确定</view>
			</view>
		</view>
	</view>
</template>

<script>
import { getUserToken, userLogin, setWxOpenid, roleLogin, getTenantInfoByPhone } from '@/apis/login.js';
import { hanleToken } from '@/utils/utils.js';
import { mapState ,mapActions } from 'vuex';
export default {
	data() {
		return {
			companyId: 0,
			type: 0,
			roleId: '',
			realName: '',
			roleList: [],
			userCompanyList: [],
			openid: '',
			phone: '',
			codeLoginParams: {
				verificationKey: '',
				tenantId: '',
				userId: ''
			}
		};
	},
	onLoad(opt) {
		this.type = opt.type || 0;
		this.phone = opt.phone; // 登录类型 1为验证码登录跳转过来
		this.openid = opt.openid || '';

		if (hanleToken('get', 'refresh_token')) {
			this.getTenantInfoByPhone();
			console.log(111);
		} else {
			const list = hanleToken('get', 'userCompanyInfo') || [];
			let arr = [];
			for (var i = 0; i < list.length; i++) {
				arr.push(list[i]);
			}
			this.userCompanyList = arr;
			this.roleList = arr[0].roleList;
			this.realName = arr[0].realName;
			this.codeLoginParams.verificationKey = arr[0].verificationKey;
			this.codeLoginParams.tenantId = arr[0].tenantId;
			this.codeLoginParams.userId = arr[0].userId;
			console.log(222);
		}
	},
	computed: {
		...mapState('user', ['userinfo'])
	},
	methods: {

		...mapActions('user', ['reSetRoutes', 'getRoutes']),
		changeCompany(res, index) {
			console.log(res);
			this.companyId = index;
			this.roleList = this.userCompanyList.find(item => item.tenantId == res.tenantId).roleList;
			this.roleId = '';
			this.codeLoginParams.verificationKey = res.verificationKey;
			this.codeLoginParams.tenantId = res.tenantId;
			this.codeLoginParams.userId = res.userId;
			this.realName = res.realName;
		},
		getTenantInfoByPhone() {
			getTenantInfoByPhone({
				phone: this.phone,
			}).then((res) => {
				const list = res.data || [];
				let arr = [];
				for (var i = 0; i < list.length; i++) {
					arr.push(list[i]);
				}
				this.userCompanyList = arr;
				this.companyId = arr.findIndex(item => item.tenantId == this.userinfo.tenant_id);
				this.roleList = arr[this.companyId].roleList;
				this.realName = arr[this.companyId].realName;
				this.codeLoginParams.verificationKey = arr[this.companyId].verificationKey;
				this.codeLoginParams.tenantId = arr[this.companyId].tenantId;
				this.codeLoginParams.userId = arr[this.companyId].userId;
			});
		},
		changeRole(item) {
			this.roleId = item.id;
		},
		// //选择角色去首页
		toIndex() {
			if (!this.roleId) {
				uni.showToast({
					title: '请先选择账号登录的公司和角色',
					icon: 'none'
				});
				return;
			}
			if (!this.openid && this.phone) {
				hanleToken('set', 'roleId', this.roleId);
				// return
				this.codeLogin(this.codeLoginParams); // 没有openid 短信登录
				return;
			}
			uni.showLoading({
				title: '授权中',
				mask: true
			});
			// 微信授权登录
			hanleToken('set', 'roleId', this.roleId);
			getUserToken({
				openid: this.openid || '',
				userId: this.codeLoginParams.userId,
			}).then(res => {
				if (res.code === 200) {
					this.reSetRoutes();// 重置路由
					uni.hideLoading();

					hanleToken('set', 'token', res.data.token_type + ' ' + res.data.access_token);
					hanleToken('set', 'refresh_token', res.data.refresh_token);
					// hanleToken('set', 'userData', res.data);
					this.$store.commit('user/setUserinfo', res.data);
					this.setWxOpenid(this.codeLoginParams.userId);
					uni.showToast({
						title: '登录成功',
						icon: 'none'
					});
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/home/index'
						});
					}, 200);
				}
			}).catch(err => {
				uni.hideLoading();
			});
		},
		// 旧的选择
		// toIndex(obj) {
		// 	if (!this.openid && this.phone) {
		// 		console.log(obj,9999)
		// 		return
		// 		this.codeLogin(obj); //没有openid 短信登录
		// 		return;
		// 	}
		// 	uni.showLoading({
		// 		title: '授权中',
		// 		mask: true
		// 	});
		// 	getUserToken({
		// 		openid: this.openid || '',
		// 		userId: obj.userId
		// 	}).then(res => {
		// 		if (res.code === 200) {
		// 			uni.hideLoading();
		// 			hanleToken('set', 'token', res.data.token_type + ' ' + res.data.access_token);
		// 			hanleToken('set', 'refresh_token', res.data.refresh_token);
		// 			hanleToken('set', 'userData', res.data);
		// 			this.$store.commit('user/setUserinfo', res.data);
		// 			this.setWxOpenid(obj.userId);
		// 			uni.showToast({
		// 				title: '登录成功',
		// 				icon: 'none'
		// 			});
		// 			setTimeout(() => {
		// 				uni.reLaunch({
		// 					url: '/pages/index/index'
		// 				});
		// 			}, 200);
		// 		}
		// 	});
		// },

		// 更新微信openid
		setWxOpenid(userId) {
			uni.login({
				success: res => {
					setWxOpenid({
						appid: this.$config.appId,
						code: res.code,
						userId
					}).then(res => { });
				},
				fail(err) { }
			});
		},
		// 验证码登录
		codeLogin(obj) {
			const params = {
				grant_type: 'phone',
				scope: 'all',
				username: this.phone,
				password: obj.verificationKey,
				tenantId: obj.tenantId
			};
			uni.showLoading({
				title: '登录中'
			});
			roleLogin(params)
				.then(async res => {
					console.log(res, '登录接口');
					if (res.code === 200) {
						this.reSetRoutes();// 重置路由
						uni.hideLoading();
						uni.showToast({
							title: '登录成功',
							icon: 'none'
						});
						hanleToken('set', 'token', res.data.token_type + ' ' + res.data.access_token);
						hanleToken('set', 'refresh_token', res.data.refresh_token);
						hanleToken('set', 'userData', res.data);
						// this.setWxOpenid(obj.userId);
						this.setWxOpenid(this.roleId);
						this.$store.commit('user/setUserinfo', res.data);
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/home/index'
							});
						}, 200);
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				})
				.catch(err => {
					console.log('err', err);

					uni.hideLoading();
					uni.showModal({
						title: '提示',
						content: `登录失败${err.errMsg ? '，请检查网络' : ''}`,
						showCancel: false,
						success() {
							// #ifndef H5 
							uni.navigateBack();
							// #endif

							// #ifdef H5 
							uni.navigateTo({
								url: '/pages/login/index'
							});
							// #endif
						}
					});
				});
		}
	}
};
</script>

<style lang="scss">
page {
	background: #f8f8f8;
}

.com_wrapper {
	.com_title {
		display: flex;
		justify-content: center;
		margin: 20rpx 0;
		font-size: 24rpx;
		color: #999999;
	}

	.com_item {
		display: flex;
		flex-direction: row;
		align-items: center;
		width: 710rpx;
		margin: 0 auto;
		background-color: #ffffff;
		height: 148rpx;
		border-radius: 8rpx;
		margin-bottom: 30rpx;

		.item_L {
			flex: 1;
			margin: 0 20rpx;

			text {
				display: block;
				font-size: 28rpx;
				color: #333333;
			}

			text:nth-child(2) {
				font-size: 24rpx;
				color: #666666;
			}
		}

		.item_R {
			flex: 0 0 50rpx;

			text {
				display: block;
				width: 16rpx;
				height: 16rpx;
				border-right: 2rpx #cccccc solid;
				border-bottom: 2rpx #cccccc solid;
				transform: rotate(-45deg);
			}
		}
	}

	.switch_role {
		height: 100vh;
		background: pink;

		.switch_role_content {
			height: calc(100% - 70rpx);
			display: flex;

			.left,
			.right {
				display: flex;
				flex-direction: column;
				font-size: 28rpx;
				color: #333;

				.header {
					height: 66rpx;
					display: flex;
					align-items: center;
					padding: 0 32rpx;
					font-size: 24rpx;
					color: #999;
				}

				.companyList {
					.companyList_item {
						padding: 32rpx;
					}
				}
			}

			.left {
				background-color: #fff;
				width: 420rpx;
				box-sizing: border-box;
			}

			.right {
				background: #f8f8f8;
				padding: 0 24rpx;
				flex: 1;

				.header {
					padding: 0;
				}

				.companyList {
					.companyList_item {
						padding: 32rpx 0;
					}
				}
			}

			.activeCom {
				color: #0091ff;
				background: #f8f8f8;
			}
		}

		.bottom {
			display: flex;
			justify-content: center;
			padding: 14rpx;
			background-color: #fff;
			position: fixed;
			bottom: 0;
			width: 100%;
			box-sizing: border-box;

			/* #ifdef H5 */
			padding-bottom: constant(safe-area-inset-bottom);  
			padding-bottom: env(safe-area-inset-bottom);  
			/* #endif */

			.submit {
				width: 100%;
				background: #0091ff;
				border-radius: 8rpx;
				color: #fff;
				height: 70rpx;
				display: flex;
				align-items: center;
				font-size: 28rpx;
				justify-content: center;
			}
		}
	}
}
</style>
